/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin.controller;

import admin.hibernate.model.dao.AdminLoaiSanPhamDAO;
import admin.hibernate.model.dao.AdminSanPhamDAO;
import hibernate.model.dao.LoaiSanPhamDAO;
import hibernate.pojo.Loaisanpham;
import hibernate.pojo.Sanpham;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadException;

/**
 *
 * @author phathuynh
 */
@WebServlet(name = "admindealprocesscontroller", urlPatterns = {"/admindealprocesscontroller"})
public class admindealprocesscontroller extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException, FileUploadException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try 
        {
            request.setCharacterEncoding("UTF-8");
            String action = request.getParameter("action");
            if (action != null) 
            {
                //<editor-fold defaultstate="collapsed" desc="Xem Trang Them">
                // Thêm sản phẩm
                if (action.equals("addingdeal")) 
                {
                    List<Loaisanpham> arrLoaiSanPham = AdminLoaiSanPhamDAO.AdminLayDanhSachLoaiSanPhamHQL();
                    request.setAttribute("DanhSachLoaiSanPham", arrLoaiSanPham);
                    request.getRequestDispatcher("Admin/pagestile/addingdeal.jsp").forward(request, response);
                }
                //</editor-fold>
                
                //<editor-fold defaultstate="collapsed" desc="Xem trang cập nhật deal">
                // Xem trang cập nhật sản phẩm
                if (action.equals("updatingdeal")) 
                {
                    String masanpham = request.getParameter("masanpham");
                    if (masanpham != null) 
                    {
                        int maSanPham = Integer.parseInt(masanpham);
                        Sanpham sanpham = AdminSanPhamDAO.getProductByID(maSanPham);
                        if (sanpham != null) 
                        {
                            request.setAttribute("DealCapNhat", sanpham);
                            List<Loaisanpham> arrLoaiSanPham = AdminLoaiSanPhamDAO.AdminLayDanhSachLoaiSanPhamHQL();
                            request.setAttribute("DanhSachLoaiSanPham", arrLoaiSanPham);
                            request.getRequestDispatcher("Admin/pagestile/updatingdeal.jsp").forward(request, response);
                        }
                    }
                }
                //</editor-fold>

                //<editor-fold defaultstate="collapsed" desc="Click vào nút Xóa sản phẩm - Sản phẩm chưa bị xóa">
                if (action.equals("del")) 
                {
                    String strproductID = request.getParameter("masanpham");
                    String catalogtype = request.getParameter("catalogtype");
                    Sanpham product = AdminSanPhamDAO.getProductByID(Integer.parseInt(strproductID));
                    product.setTinhTrangXoa(0);
                    boolean delResult = AdminSanPhamDAO.updateProduct(product);
                    if (delResult == true) 
                    {
                        List<Sanpham> arrSanPham = LoaiSanPhamDAO.LayDanhSachSanPhamTheoLoaiHQL(product.getLoaisanpham().getTenTrang());
                        request.setAttribute("DanhSachSanPhamTheoLoai", arrSanPham);
                        response.sendRedirect("admincatalogcontroller?action=listdealbycatalog&catalogtype="+catalogtype);
                        return;
                        //request.getRequestDispatcher("Admin/pagestile/listdealbycatalog.jsp").forward(request, response);
                    }
                }
                //</editor-fold>
                
                //<editor-fold defaultstate="collapsed" desc="Click vào nút Xóa sản phẩm - Sản phẩm đã bị xóa & phục hồi lại">
                if (action.equals("redel")) 
                {
                    String strproductID = request.getParameter("masanpham");
                    String catalogtype = request.getParameter("catalogtype");
                    Sanpham product = AdminSanPhamDAO.getProductByID(Integer.parseInt(strproductID));
                    product.setTinhTrangXoa(1);
                    boolean delResult = AdminSanPhamDAO.updateProduct(product);
                    if (delResult == true) 
                    {
                        List<Sanpham> arrSanPham = LoaiSanPhamDAO.LayDanhSachSanPhamTheoLoaiHQL(product.getLoaisanpham().getTenTrang());
                        request.setAttribute("DanhSachSanPhamTheoLoai", arrSanPham);
                        response.sendRedirect("admincatalogcontroller?action=listdealbycatalog&catalogtype="+catalogtype);
                        return;
                        //request.getRequestDispatcher("Admin/pagestile/listdealbycatalog.jsp").forward(request, response);
                    }
                }
                //</editor-fold>

                //<editor-fold defaultstate="collapsed" desc="Cập nhật sản phẩm">
                if (action.equals("update")) 
                {
                    String strproductID = request.getParameter("masanpham");
                    int intProductID = Integer.parseInt(strproductID);
                    Sanpham product = AdminSanPhamDAO.getProductByID(intProductID);
                    String productName = (String) request.getParameter("txtTenSanPham");
                    String strCategory = (String) request.getParameter("cboLoaiSanPham");
                    int intCategory = 0;
                    if (!strCategory.equals("")) 
                    {
                        intCategory = Integer.parseInt(strCategory);
                    }
                    String productTitle = (String) request.getParameter("txtTieuDeSanPham");
                    String strprice = (String) request.getParameter("txtGiaBan");
                    double douprice = 0;
                    if (!strprice.equals("")) 
                    {
                        douprice = Double.parseDouble(strprice);
                    }

                    String strcost = (String) request.getParameter("txtTriGia");
                    double doucost = 0;
                    if (!strcost.equals("")) 
                    {
                        doucost = Double.parseDouble(strcost);
                    }

                    String strsave = (String) request.getParameter("txtTietKiem");
                    double dousave = 0;
                    if (!strsave.equals("")) 
                    {
                        dousave = Double.parseDouble(strsave);
                    }
                    String strDateFrom = (String) request.getParameter("txtNgayBatDauKhuyenMai");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    Date dateFrom = null;
                    if (!strDateFrom.equals("")) 
                    {
                        dateFrom = sdf.parse(strDateFrom);
                        //dateFrom = sdf.format(strDateFrom);
                    }
                    Date dateExpire = null;
                    String strDateExpire = (String) request.getParameter("txtNgayKetThucKhuyenMai");
                    if (!strDateExpire.equals("")) 
                    {
                        dateExpire = sdf.parse(strDateExpire);
                    }
                    String strpromotionDuration = (String) request.getParameter("txtThoiGianKhuyenMai");
                    int intpromotionDuration = 0;
                    if (!strpromotionDuration.equals(""))
                    {
                        intpromotionDuration = Integer.parseInt(strpromotionDuration);
                    }

                    String strhit = (String) request.getParameter("txtLuotMua");
                    int intHit = 0;
                    if (!strhit.equals("")) 
                    {
                        intHit = Integer.parseInt(strhit);
                    }
                    String strpromotionState = (String) request.getParameter("txtTinhTrangKhuyenMai");
                    int intpromotionState = 0;
                    if (!strpromotionState.equals("")) 
                    {
                        intpromotionState = Integer.parseInt(strpromotionState);
                    }

                    String strdelState = (String) request.getParameter("txtTinhTrangXoa");
                    int intDelState = 0;
                    if (!strdelState.equals("")) 
                    {
                        intDelState = Integer.parseInt(strdelState);
                    }
                    String note = (String) request.getParameter("txtGhiChu");
                    
                    String pathImage = request.getParameter("fileUploadAnh");
                    
                    Loaisanpham category = LoaiSanPhamDAO.getCategoryByID(intCategory);
                    product.setLoaisanpham(category);
                    product.setTenSanPham(productName);
                    product.setTieuDeSanPham(productTitle);
                    product.setGiaBan(douprice);
                    product.setTriGia(doucost);
                    product.setTietKiem(dousave);
                    product.setNgayBatDauKhuyenMai(dateFrom);
                    product.setNgayHetHanKhuyenMai(dateExpire);
                    product.setLuotMua(intHit);
                    product.setTinhTrangKhuyenMai(intpromotionState);
                    product.setThoiGianKhuyenMai(intpromotionDuration);
                    product.setTinhTrangXoa(intDelState);
                    product.setGhiChu(note);
                    product.setAnhDaiDien(pathImage);
                    boolean res = AdminSanPhamDAO.updateProduct(product);
                    if(res == true) 
                    {
                        List<Sanpham> arrSanPham = LoaiSanPhamDAO.LayDanhSachSanPhamTheoLoaiHQL(category.getTenTrang());
                        request.setAttribute("DanhSachSanPhamTheoLoai", arrSanPham);
                        request.getRequestDispatcher("Admin/pagestile/listdealbycatalog.jsp").forward(request, response);
                    } 
                    else 
                    {
                        out.print("Không cập nhật được");
                    }
                }
                //</editor-fold>

                //<editor-fold defaultstate="collapsed" desc="Thêm sản phẩm">
                if (action.equals("add")) 
                {
                    Sanpham product = new Sanpham();
                    String productName = (String) request.getParameter("txtTenSanPham");
                    String strCategory = (String) request.getParameter("cboLoaiSanPham");
                    Loaisanpham category = null;
                    if (!strCategory.equals("")) 
                    {
                        int intCat = Integer.parseInt(strCategory);
                        category = AdminLoaiSanPhamDAO.getProductByID(intCat);
                    }
                    String productTitle = (String) request.getParameter("txtTieuDeSanPham");
                    String strprice = (String) request.getParameter("txtGiaBan");
                    double douprice = 0;
                    if (!strprice.equals("")) 
                    {
                        douprice = Double.parseDouble(strprice);
                    }

                    String strcost = (String) request.getParameter("txtTriGia");
                    double doucost = 0;
                    if (!strcost.equals("")) 
                    {
                        doucost = Double.parseDouble(strcost);
                    }

                    String strDateFrom = (String) request.getParameter("txtNgayBatDauKhuyenMai");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    Date dateFrom = null;
                    if (!strDateFrom.equals("")) 
                    {
                        dateFrom = sdf.parse(strDateFrom);
                    }
                    Date dateExpire = null;
                    String strDateExpire = (String) request.getParameter("txtNgayKetThucKhuyenMai");
                    if (!strDateExpire.equals("")) 
                    {
                        dateExpire = sdf.parse(strDateExpire);
                    }
                    String strpromotionDuration = (String) request.getParameter("txtThoiGianKhuyenMai");
                    int intpromotionDuration = 0;
                    if (!strpromotionDuration.equals("")) 
                    {
                        intpromotionDuration = Integer.parseInt(strpromotionDuration);
                    }
                    String note = (String) request.getParameter("txtGhiChu");
                    
                    String pathImage = request.getParameter("fileUploadAnh");
                    
                    product.setLoaisanpham(category);
                    product.setTenSanPham(productName);
                    product.setTieuDeSanPham(productTitle);
                    product.setGiaBan(douprice);
                    product.setTriGia(doucost);
                    double dousave = doucost - douprice;
                    product.setTietKiem(dousave);
                    product.setNgayBatDauKhuyenMai(dateFrom);
                    product.setNgayHetHanKhuyenMai(dateExpire);
                    product.setLuotMua(0);
                    product.setTinhTrangKhuyenMai(1);
                    product.setThoiGianKhuyenMai(intpromotionDuration);
                    product.setTinhTrangXoa(1);
                    product.setGhiChu(note);
                    product.setAnhDaiDien(pathImage);
                           
                    boolean res = AdminSanPhamDAO.addProduct(product);
                    if (res == true) 
                    {
                        int recentlyAddedProduct = AdminSanPhamDAO.getRecentlyAddedProduct();
                        response.sendRedirect("admindealdetailcontroller?action=view&masanpham=" + recentlyAddedProduct);
                        return;
                    } 
                    else // xem lại phần nếu không thêm được thì sendRedirec ntn?
                    {
                        out.print("Không thêm sản phẩm được.");
                    }
                }

                //</editor-fold>
            }
        } catch (Exception ex) {
            out.println(ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (FileUploadException ex) {
                Logger.getLogger(admindealprocesscontroller.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ParseException ex) {
            Logger.getLogger(admindealprocesscontroller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (FileUploadException ex) {
                Logger.getLogger(admindealprocesscontroller.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ParseException ex) {
            Logger.getLogger(admindealprocesscontroller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
